package com.aim.config.shiro;

import com.aim.common.constant.Symbol;
import com.aim.common.listener.ConfigListener;
import com.aim.common.util.ConverterUtils;
import com.aim.common.util.WebUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

/**
 * @AUTO 权限自定义检查
 * @Author AIM
 * @DATE 2019/5/9
 */
@Service
@Transactional(readOnly = true)
public class PermissionCheckService {

    public boolean check(Object[] permissions) {
        ShiroUser user = ShiroKit.getUser();
        if (null == user) {
            return false;
        }
        ArrayList<Object> list = ConverterUtils.newArrayList(permissions);
        CharSequence[] cs = list.toArray(new CharSequence[list.size()]);
        String join = WebUtil.join(Symbol.COMMA, cs);
        if (ShiroKit.hasAnyRoles(join)) {
            return true;
        }
        return false;
    }

    public boolean checkAll() {
        HttpServletRequest request = WebUtil.getRequest();
        ShiroUser user = ShiroKit.getUser();
        if (null == user) {
            return false;
        }
        String requestURI = request.getRequestURI().replaceFirst(ConfigListener.getConf().get("contextPath"), "");
        String[] str = requestURI.split("/");
        if (str.length > 3) {
            requestURI = "/" + str[1] + "/" + str[2];
        }
        if (ShiroKit.hasPermission(requestURI)) {
            return true;
        }
        return false;
    }
}
